package com.bruce.spring.http.service.cgroup;

import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CgroupV2ProviderWithFiles extends CgroupV2BaseProvider implements Closeable {
    private static final String CPU_STAT_PATH = "/sys/fs/cgroup/cpu.stat";

    public CgroupV2ProviderWithFiles() throws IOException {

    }

    @Override
    public long getCurrentCpuTime() throws IOException {
        long userUsec = 0;
        long systemUsec = 0;

        // 每次读取都重新加载文件内容（无需复用句柄）
        byte[] contentBytes = Files.readAllBytes(Paths.get(CPU_STAT_PATH));
        if (contentBytes.length == 0) {
            throw new IOException("cpu.stat文件内容为空");
        }

        // 转换为字符串并按行解析
        String content = new String(contentBytes);
        String[] lines = content.split("\n");

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            // 匹配目标字段并提取数值
            if (line.startsWith(USER_USEC)) {
                int spaceIndex = line.indexOf(SPACE);
                String valueStr = line.substring(spaceIndex + 1).trim();
                userUsec = parseLongSafely(valueStr);
            } else if (line.startsWith(SYSTEM_USEC)) {
                int spaceIndex = line.indexOf(SPACE);
                String valueStr = line.substring(spaceIndex + 1).trim();
                systemUsec = parseLongSafely(valueStr);
            }

            // 提前退出条件
            if (userUsec > 0 && systemUsec > 0) break;
        }

        // 校验结果
        if (userUsec == 0 && systemUsec == 0) {
            throw new IOException("未解析到有效CPU时间（user_usec和system_usec均为0）");
        }

        return (userUsec + systemUsec) * 1000; // 微秒转纳秒
    }

    private long parseLongSafely(String valueStr) {
        try {
            return Long.parseLong(valueStr);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    @Override
    public void close() throws IOException {
        // 无需手动释放资源（Files.readAllBytes会自动关闭）
    }
}
